package cn.zhentao.service.impl;

import cn.zhentao.mapper.VTaskPackagesMapper;
import cn.zhentao.pojo.VTaskPackages;
import cn.zhentao.service.IVTaskPackagesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author mp
 * @since 2025-06-22
 */
@Service
public class VTaskPackagesServiceImpl extends ServiceImpl<VTaskPackagesMapper, VTaskPackages> implements IVTaskPackagesService {

    @Override
    public Map<String, Long> getTaskPackageStats() {
        QueryWrapper<VTaskPackages> queryWrapper = new QueryWrapper<>();

        // 使用 SQL 的 COUNT 和 CASE WHEN 函数，在一次查询中统计出所有状态的数量
        queryWrapper.select(
                "COUNT(CASE WHEN package_status = 0 THEN 1 END) as pending",
                "COUNT(CASE WHEN package_status = 1 THEN 1 END) as delivering",
                "COUNT(CASE WHEN package_status = 2 THEN 1 END) as completed",
                "COUNT(CASE WHEN package_status = 3 THEN 1 END) as cancelled"
        );

        // getMap 会执行上面的 select 查询并返回一个 Map
        Map<String, Object> dbResult = this.getMap(queryWrapper);

        // 为确保类型安全和处理null值，我们手动转换一下
        Map<String, Long> stats = new HashMap<>();
        stats.put("pending", ((Number) dbResult.getOrDefault("pending", 0)).longValue());
        stats.put("delivering", ((Number) dbResult.getOrDefault("delivering", 0)).longValue());
        stats.put("completed", ((Number) dbResult.getOrDefault("completed", 0)).longValue());
        stats.put("cancelled", ((Number) dbResult.getOrDefault("cancelled", 0)).longValue());

        return stats;
    }
}
